import 'dart:convert' as convert;
import 'dart:core';

import 'package:inspiration_f/model/home_mode.dart';
import 'package:inspiration_f/utils/string.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 本地存储
class XMPreferences {
  // 本地存储的统一实例
  SharedPreferences? sharePreInstance;
  // 本地json数组
  List<String> localJsonArr = [];
  List<HomeModel> localModelArr = [];

  // 单例 - BEGIN
  factory XMPreferences() => _getInstance();
  static XMPreferences get instance => _getInstance();
  // 静态变量_instance，存储唯一对象
  static XMPreferences? _instance;
  // 获取唯一对象
  static XMPreferences _getInstance() {
    _instance ??= XMPreferences._internal();
    return _instance!;
  }
  // 单例 - END

  //初始化...
  XMPreferences._internal() {
    //初始化其他操作...
    _getSharedPreferencesAction();
  }

  // 获取存储实例 -- 如果在initState等方法调用的话，必须返回Future，否则会阻塞线程
  Future<void> _getSharedPreferencesAction() async {
    print("初始化了sharePreInstance");
    await SharedPreferences.getInstance().then((value) {
      sharePreInstance = value;
    });
    localJsonArr = sharePreInstance?.getStringList(localJsonArrKey) ?? [];
    _initLocalModelArr();
  }

  _initLocalModelArr() {
    localModelArr = [];
    localJsonArr.forEach((jsonString) {
      var model = HomeModel.fromJson(convert.jsonDecode(jsonString));
      localModelArr.add(model);
    });

    // 首次安装 ---- BEGIN
    // 判断是否是首次安装
    bool isFirstInstalled =
        sharePreInstance?.getBool("isFirstInstalled") ?? true;
    if (isFirstInstalled) {
      _addFirstInstallData();
    }
    sharePreInstance?.setBool("isFirstInstalled", false);
    // 首次安装 ---- END
  }

  // 添加首次安装数据
  _addFirstInstallData() {
    HomeModel model1 = HomeModel(id: "1", title: "22左滑 -- 删除数据", colorInt: 0);
    addHomeModel(model1);
    HomeModel model2 =
        HomeModel(id: "2", title: "点击右下角按钮 -- 添加数据", colorInt: 1);
    addHomeModel(model2);
    HomeModel model3 = HomeModel(id: "3", title: "长按列表 -- 拖动排序", colorInt: 2);
    addHomeModel(model3);
  }

  removeHomeModel(HomeModel? homeModel) {
    if (homeModel == null) {
      return;
    }
    localModelArr.removeWhere((element) => element.id == homeModel.id);
    // 把最新的model数组更新到json数组中，并保存到本地。
    refreshLocalData();
  }

  addHomeModel(HomeModel? homeModel) {
    if (homeModel == null) {
      return;
    }
    bool isExist = false;
    localModelArr.asMap().forEach((index, value) {
      if (value.id == homeModel.id) {
        localModelArr[index] = homeModel;
        isExist = true;
      }
    });
    if (!isExist) {
      localModelArr.insert(0, homeModel);
    }
    // 去空
    localModelArr.removeWhere((model) {
      return model.title.isEmpty;
    });

    // 把最新的model数组更新到json数组中，并保存到本地。
    refreshLocalData();
  }

  // 刷新本地数据
  refreshLocalData() {
    List<String> lastLocalJsonArr = [];
    for (var model in localModelArr) {
      var json = convert.jsonEncode(model);
      lastLocalJsonArr.add(json);
    }
    localJsonArr = lastLocalJsonArr;
    sharePreInstance?.setStringList(localJsonArrKey, localJsonArr ?? []);
  }
}
